package org.wcms.surrounded.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.wcms.surrounded.model.User;
import org.wcms.surrounded.persistence.HighScoresService;
import org.wcms.surrounded.web.data.HighScoresData;
import org.wcms.surrounded.web.data.ResponseData;

import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;

@RequestScoped
public class HighScoresAjaxHandler implements AjaxHandler {

    private final HighScoresService highScoresService;
    
    @Inject
    public HighScoresAjaxHandler(HighScoresService highScoresService) {
        this.highScoresService = highScoresService;
    }
    
    @Override
    public ResponseData handle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    	Map<User, List<Integer>> highScores = highScoresService.getHighScores();
    	HighScoresData data = new HighScoresData();
        
        List<Map<String, String>> result = new ArrayList<Map<String,String>>();
        for (Entry<User, List<Integer>> entry : highScores.entrySet()) {
            
            User user = entry.getKey();
        	
        	for (Integer score : entry.getValue()) {
        	    Map<String, String> userScoreData = new HashMap<String,String>();
            	userScoreData.put("userName", user.getUserName());
            	userScoreData.put("userPicURL", user.getPicURL());
            	userScoreData.put("userScore", String.valueOf(score));
            	
            	result.add(userScoreData);
        	}
        }
        
        Collections.sort(result, new Comparator<Map<String,String>>() {

			@Override
			public int compare(Map<String, String> o1, Map<String, String> o2) {
				return (Integer.parseInt(o2.get("userScore")) - Integer.parseInt(o1.get("userScore")));
			}
        	
        });
        
        data.setHighScores(result);
        
        return data;
    }

}
